// 初始化图表
function initCharts() {
    // 温度图表
    const temperatureChart = echarts.init(document.getElementById('temperatureChart'));
    const temperatureOption = {
        title: {
            text: '24小时温度变化'
        },
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            data: Array.from({length: 24}, (_, i) => `${i}:00`)
        },
        yAxis: {
            type: 'value',
            name: '温度(°C)'
        },
        series: [{
            data: generateRandomData(24, 20, 30),
            type: 'line',
            smooth: true
        }]
    };
    temperatureChart.setOption(temperatureOption);

    // 湿度图表
    const humidityChart = echarts.init(document.getElementById('humidityChart'));
    const humidityOption = {
        title: {
            text: '24小时湿度变化'
        },
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            data: Array.from({length: 24}, (_, i) => `${i}:00`)
        },
        yAxis: {
            type: 'value',
            name: '湿度(%)'
        },
        series: [{
            data: generateRandomData(24, 50, 80),
            type: 'line',
            smooth: true
        }]
    };
    humidityChart.setOption(humidityOption);
}

// 生成随机数据
function generateRandomData(length, min, max) {
    return Array.from({length}, () => 
        Math.floor(Math.random() * (max - min + 1) + min)
    );
}

// 更新实时数据
function updateRealTimeData() {
    const updateValue = (elementId, newValue) => {
        const element = document.getElementById(elementId);
        element.classList.remove('value-update');
        // 触发重排以重新启动动画
        void element.offsetWidth;
        element.classList.add('value-update');
        element.textContent = newValue;
    };

    // 生成随机数据并更新
    const temperature = Math.floor(Math.random() * (30 - 20 + 1) + 20);
    const humidity = Math.floor(Math.random() * (80 - 50 + 1) + 50);
    const light = Math.floor(Math.random() * (100000 - 50000 + 1) + 50000);
    const soilMoisture = Math.floor(Math.random() * (60 - 30 + 1) + 30);

    updateValue('temperature', `${temperature}°C`);
    updateValue('humidity', `${humidity}%`);
    updateValue('light', `${light} lux`);
    updateValue('soil-moisture', `${soilMoisture}%`);

    // 检查预警条件
    checkAlerts(temperature, humidity, soilMoisture);

    // 更新数据总览卡片
    updateValue('avgTemp', `${(temperature - 2 + Math.random() * 4).toFixed(1)}°C`);
    updateValue('avgHumidity', `${humidity}%`);
    updateValue('currentLight', `${light} lux`);
    updateValue('soilStatus', getSoilStatus(soilMoisture));
}

// 获取土壤状态描述
function getSoilStatus(moisture) {
    if (moisture < 35) return '偏干';
    if (moisture > 70) return '偏湿';
    return '适宜';
}

// 预警检查
function checkAlerts(temperature, humidity, soilMoisture) {
    const alertList = document.getElementById('alertList');
    alertList.innerHTML = '';

    if (temperature > 28) {
        addAlert('温度过高警告：请注意防暑降温');
    }
    if (humidity > 75) {
        addAlert('湿度过高警告：注意防范病害发生');
    }
    if (soilMoisture < 35) {
        addAlert('土壤水分不足：建议及时灌溉');
    }
}

// 添加预警信息
function addAlert(message) {
    const alertList = document.getElementById('alertList');
    const alertDiv = document.createElement('div');
    alertDiv.className = 'alert';
    alertDiv.textContent = message;
    alertList.appendChild(alertDiv);
}

// 天气预报数据生成函数优化
function generateForecast() {
    const forecastList = document.getElementById('forecastList');
    const days = ['今天', '明天', '后天', '第四天', '第五天'];
    const weatherTypes = [
        { type: '晴', icon: '☀️', wind: '东北风 3级', humidity: '45%' },
        { type: '多云', icon: '⛅', wind: '东风 2级', humidity: '55%' },
        { type: '阴', icon: '☁️', wind: '东南风 4级', humidity: '65%' },
        { type: '小雨', icon: '🌧️', wind: '南风 3级', humidity: '75%' }
    ];
    
    forecastList.innerHTML = days.map(day => {
        const temp = Math.floor(Math.random() * (30 - 15) + 15);
        const tempMin = temp - Math.floor(Math.random() * 5);
        const weather = weatherTypes[Math.floor(Math.random() * weatherTypes.length)];
        return `
            <div class="forecast-item">
                <h4>${day}</h4>
                <div class="forecast-weather-icon">${weather.icon}</div>
                <div class="forecast-weather">${weather.type}</div>
                <div class="forecast-temp">${tempMin}°C ~ ${temp}°C</div>
                <div class="forecast-details">
                    <div>${weather.wind}</div>
                    <div>湿度 ${weather.humidity}</div>
                </div>
            </div>
        `;
    }).join('');

    // 添加横向滚动提示
    if (forecastList.scrollWidth > forecastList.clientWidth) {
        const scrollHint = document.createElement('div');
        scrollHint.className = 'scroll-hint';
        scrollHint.textContent = '← 滑动查看更多 →';
        scrollHint.style.textAlign = 'center';
        scrollHint.style.color = '#666';
        scrollHint.style.fontSize = '0.9rem';
        scrollHint.style.marginTop = '0.5rem';
        forecastList.parentNode.appendChild(scrollHint);

        // 3秒后隐藏提示
        setTimeout(() => {
            scrollHint.style.display = 'none';
        }, 3000);
    }
}

// 添加天气图标动画效果
function addWeatherAnimation() {
    const icons = document.querySelectorAll('.forecast-weather-icon');
    icons.forEach(icon => {
        icon.style.animation = 'weather-bounce 2s infinite';
    });
}

// 更新农事建议
function updateFarmingAdvice() {
    const temperature = parseInt(document.getElementById('temperature').textContent);
    const humidity = parseInt(document.getElementById('humidity').textContent);
    const soilMoisture = parseInt(document.getElementById('soil-moisture').textContent);

    // 作物管理建议
    let cropAdvice = '';
    if (temperature > 28) {
        cropAdvice = '温度偏高，建议采取遮阳措施';
    } else if (temperature < 15) {
        cropAdvice = '温度偏低，注意作物保温';
    } else {
        cropAdvice = '温度适宜，可进行常规田间管理';
    }
    document.getElementById('cropAdvice').textContent = cropAdvice;

    // 灌溉建议
    let irrigationAdvice = '';
    if (soilMoisture < 35) {
        irrigationAdvice = '土壤水分不足，建议及时灌溉';
    } else if (soilMoisture > 70) {
        irrigationAdvice = '土壤水分充足，暂停灌溉';
    } else {
        irrigationAdvice = '土壤墒情适宜，保持现有灌溉方案';
    }
    document.getElementById('irrigationAdvice').textContent = irrigationAdvice;

    // 病虫害防治建议
    let pestAdvice = '';
    if (humidity > 75) {
        pestAdvice = '湿度较高，注意防范病害发生';
    } else if (temperature > 25 && humidity > 60) {
        pestAdvice = '温湿度适宜病虫害滋生，建议预防性喷药';
    } else {
        pestAdvice = '病虫害发生风险较低，继续观察';
    }
    document.getElementById('pestAdvice').textContent = pestAdvice;
}

// 显示添加病虫害记录的模态框
function showAddPestModal() {
    // 实现模态框显示逻辑
}

// 加载病虫害数据
function loadPestData() {
    // 从后端获取数据并更新页面
}

// 更新病虫害状态
function updatePestStatus(pestId, status) {
    // 更新处理状态的逻辑
}

// 初始化页面
document.addEventListener('DOMContentLoaded', function() {
    initCharts();
    updateRealTimeData();
    generateForecast();
    updateFarmingAdvice();
    addWeatherAnimation();
    loadPestData();
    
    // 定时更新数据
    setInterval(() => {
        updateRealTimeData();
        updateFarmingAdvice();
    }, 30000);
    
    // 每天更新一次天气预报
    setInterval(generateForecast, 24 * 60 * 60 * 1000);
}); 